package com.joven.shelltest.utils.pdf;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.File;
import java.io.IOException;

/**
 * @Author wzj
 * @Date 2023-08-24 14:34
 **/
public class PdfWaterMarkUtil2 {

    public static void waterMarkPdfbox(String fileName, String watermarkText, String newFileName) throws IOException {
        // 读取原始 PDF 文件
        PDDocument document = PDDocument.load(new File(fileName));

        // 遍历 PDF 中的所有页面
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            PDPage page = document.getPage(i);
            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
//            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            // 设置字体和字号
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);
            // 设置透明度
            contentStream.setNonStrokingColor(200, 200, 200);
            // 添加文本水印
            contentStream.beginText();
            // 设置水印位置
            contentStream.newLineAtOffset(100, 100);
            // 设置水印内容
            contentStream.showText(watermarkText);
            contentStream.endText();
            contentStream.close();
        }
        // 保存修改后的 PDF 文件
        document.save(new File(newFileName));
        document.close();
    }


    public static void main(String[] args) throws Exception {
        waterMarkPdfbox("D:\\image\\page2.pdf", "616807982", "D:\\image\\testPdfBox.pdf");
    }


}
